<template>
  <div>
    <t-popconfirm :visible="visible" theme="danger" hover="color" placement="bottom-right"
                  :confirm-btn="{ size: 'medium', content: '确定' }"
                  :cancel-btn="{ size: 'medium' }"
                  @visible-change="onVisibleChange"
                  @confirm="productAdd"
                  @cancel="productAddCancel">
      <template #icon><p></p></template>
      <template #content>
        <div style="width: 400px;">
          <h3 class="popconfirm-title">新增产品</h3>
          <div class="mt16 mb32">
            <t-form :data="formData" :rules="rules" ref="form" label-align="top" @submit="productAddConfirm">
              <t-form-item label="产品名称" name="title">
                <t-input v-model="formData.title" placeholder="请输入产品名称"></t-input>
              </t-form-item>
              <t-form-item label="产品分类" name="classify_id">
                <t-cascader v-model="formData.classify_id" :options="classifyOptions" placeholder="请选择产品分类"></t-cascader>
              </t-form-item>
            </t-form>
          </div>
        </div>
      </template>
      <t-button theme="primary">新增产品</t-button>
    </t-popconfirm>
  </div>
</template>

<script>
import {productCreateApi} from "@/api/product";

export default {
  name: 'AddProductPop',
  props: {
    classifyOptions: {
      type: Array,
      default: () => [],
    }
  },
  data() {
    return {
      visible: false,
      formData: {
        title: '',
        classify_id: '',
      },
      rules: {
        title: [{required: true, message: '请输入名称', trigger: 'blur'}],
        classify_id: [{required: true, message: '请选择分类', trigger: 'change'}]
      },
    }
  },
  methods: {
    onVisibleChange(val, context = {}) {
      // trigger 表示触发来源，可以根据触发来源自由控制 visible
      if (context && context.trigger !== 'confirm') {
        this.visible = val;
      }
    },
    // 添加仓库
    productAdd() {
      this.$refs.form.submit()
    },
    // 确定添加仓库
    productAddConfirm({validateResult, firstError}) {
      if (validateResult === true) {
        productCreateApi(this.formData).then(res => {
          this.$emit('change')
          this.$message.success(res.retmsg)
          this.formData = {
            title: '',
            classify_id: '',
          }
          this.$refs.form.reset()
          this.visible = false
        }).catch(err => {
          console.log(err)
        })
      } else {
        this.$message.warning(firstError);
      }
    },
    // 取消添加仓库
    productAddCancel() {
      this.formData = {
        title: '',
        classify_id: '',
      }
      this.$refs.form.reset()
    },
  }
}
</script>

<style lang="less" scoped>

</style>
